package com.gdc.miaosha.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdc.miaosha.constants.RedisConstant;
import com.gdc.miaosha.entity.User;
import com.gdc.miaosha.mapper.UserMapper;
import com.gdc.miaosha.service.IUserService;
import com.gdc.miaosha.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;

import java.util.Objects;

import static com.gdc.miaosha.constants.CommonConstant.DEL_FLAG_N;

/**
 * <p>
 * 登陆用户表 服务实现类
 * </p>
 *
 * @author gdc
 * @since 2022-04-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public User getByMobile(String mobile) {
        return lambdaQuery()
                .eq(User::getMobile, mobile)
                .eq(User::getDelFlag, DEL_FLAG_N)
                .one();
    }

    @Override
    public User getByToken(@NotBlank String token) {
        if (StrUtil.isBlank(token)) {
            return null;
        }
        String userJsonStr = RedisUtil.getString(RedisConstant.TOKEN_PREFIX + token);
        if (StrUtil.isBlank(userJsonStr)) {
            return null;
        }
        User user = JSON.parseObject(userJsonStr, User.class);
        // 每次获取用户信息后更新token的过期时间
        RedisUtil.expire(RedisConstant.TOKEN_PREFIX + token, RedisConstant.EXPIRED_2_DAY);
        return user;
    }

    @Override
    public User getById(Integer id) {
        User user = RedisUtil.get(RedisConstant.USER, User.class);
        if (Objects.nonNull(user)) {
            return user;
        }

        User result = baseMapper.selectById(id);
        if (Objects.isNull(result)) {
            return result;
        }
        RedisUtil.set(RedisConstant.USER + id, result);
        return result;
    }
}
